package com.file;

import com.utils.POIUtil;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * Created by Jeff on 2018/8/15.
 */
public class copy {
    public static void main(String[] args) throws Exception {
        try {
            Date startTime = new Date();
            File excelfile = new File(args[0]);
            String startPath = args[1];
            String endPath = args[2];
            //File excelfile = new File("F:/test/222.xlsx");
            //String startPath = "F:/test";
            //String endPath = "F:/test/1";
            String oldPath;
            File endfile = new File(endPath);
            int j = 0;
            List<String[]> excelList = POIUtil.readExcel(excelfile);
            ArrayList<Object> unExistFileList = new ArrayList<>();
            System.out.println("src:    " + startPath);
            System.out.println("desc:   " + endPath);
            for (String[] arr : excelList) {
                for (String cellName : arr) {
                    oldPath = startPath + "/" + cellName;
                    File srcpath = new File(oldPath);
                    if (srcpath.exists()) {
                        copy1(srcpath, endfile);
                        ++j;
                        System.out.println(cellName + "     success<" + j + ">");
                    } else {
                        unExistFileList.add(cellName);
                    }
                }
            }
            Date endTime = new Date();
            long useTime = (endTime.getTime() - startTime.getTime()) / 1000;
            System.out.println("************************* GAME OVER **************************** ALL USER " + useTime + "s");
            System.out.println("************************* NOT  FIND **************************** " + unExistFileList.size());
            for (Object s : unExistFileList) {
                System.out.println(s);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //@Test
    //public void test() {
    //    try {
    //        Date startTime = new Date();
    //        File excelfile = new File("F:/test/222.xlsx");
    //        String startPath = "F:/test";
    //        String endPath = "F:/test/1";
    //        String oldPath;
    //        File endfile = new File(endPath);
    //        int j = 0;
    //        List<String[]> excelList = POIUtil.readExcel(excelfile);
    //        ArrayList<Object> unExistFileList = new ArrayList<>();
    //        System.out.println("src:    " + startPath);
    //        System.out.println("desc:   " + endPath);
    //        for (String[] arr : excelList) {
    //            for (String cellName : arr) {
    //                oldPath = startPath + "/" + cellName;
    //                File srcpath = new File(oldPath);
    //                if (srcpath.exists()) {
    //                    copy(srcpath, endfile);
    //                    ++j;
    //                    System.out.println(cellName + "     success<" + j + ">");
    //                } else {
    //                    unExistFileList.add(cellName);
    //                }
    //            }
    //        }
    //        Date endTime = new Date();
    //        long useTime = (endTime.getTime() - startTime.getTime()) / 1000;
    //        System.out.println("************************* GAME OVER **************************** ALL USER " + useTime + "s");
    //        for (Object s : unExistFileList) {
    //            System.out.println("************************* NOT  FIND **************************** "+unExistFileList.size());
    //            System.out.println(s);
    //        }
    //    } catch (Exception e) {
    //        e.printStackTrace();
    //    }
    //}

    static FileInputStream fis = null;
    static FileOutputStream fos = null;

    public static void copy(File file, File toFile) throws Exception {
        // FileInputStream fis = null;
        // FileOutputStream fos = null;
        try {
            // FileInputStream fis;
            // FileOutputStream fos;
            byte[] b = new byte[1024];
            int a;
            if (file.isDirectory()) {
                String filepath = file.getAbsolutePath();
                filepath = filepath.replaceAll("\\\\", "/");
                String toFilepath = toFile.getAbsolutePath();
                toFilepath = toFilepath.replaceAll("\\\\", "/");
                int lastIndexOf = filepath.lastIndexOf("/");
                toFilepath = toFilepath + filepath.substring(lastIndexOf, filepath.length());
                File copy = new File(toFilepath);
                // 复制文件夹
                if (!copy.exists()) {
                    copy.mkdir();
                }
                // 遍历文件夹
                for (File f : file.listFiles()) {
                    copy(f, copy);
                }
            } else {
                if (toFile.isDirectory()) {
                    String filepath = file.getAbsolutePath();
                    filepath = filepath.replaceAll("\\\\", "/");
                    String toFilepath = toFile.getAbsolutePath();
                    toFilepath = toFilepath.replaceAll("\\\\", "/");
                    int lastIndexOf = filepath.lastIndexOf("/");
                    toFilepath = toFilepath + filepath.substring(lastIndexOf, filepath.length());
                    // 写文件
                    File newFile = new File(toFilepath);
                    fis = new FileInputStream(file);
                    fos = new FileOutputStream(newFile);
                    while ((a = fis.read(b)) != -1) {
                        fos.write(b, 0, a);
                    }
                } else {
                    // 写文件
                    fis = new FileInputStream(file);
                    fos = new FileOutputStream(toFile);
                    while ((a = fis.read(b)) != -1) {
                        fos.write(b, 0, a);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            fis.close();
            fos.close();
        }
    }

    public static void copy1(File source, File target) {
        try {
            if (source.isDirectory()) {
                String filepath = source.getAbsolutePath();
                filepath = filepath.replaceAll("\\\\", "/");
                String toFilepath = target.getAbsolutePath();
                toFilepath = toFilepath.replaceAll("\\\\", "/");
                int lastIndexOf = filepath.lastIndexOf("/");
                toFilepath = toFilepath + filepath.substring(lastIndexOf, filepath.length());
                File copy = new File(toFilepath);
                // 复制文件夹
                if (!copy.exists()) {
                    copy.mkdir();
                }
                // 遍历文件夹
                for (File f : source.listFiles()) {
                    copy1(f, copy);
                }
            } else {
                if (target.isDirectory()) {
                    String filepath = source.getAbsolutePath();
                    filepath = filepath.replaceAll("\\\\", "/");
                    String toFilepath = target.getAbsolutePath();
                    //toFilepath = toFilepath.replaceAll("\\\\", "/");
                    //int lastIndexOf = filepath.lastIndexOf("/");
                    //toFilepath = toFilepath + filepath.substring(lastIndexOf, filepath.length());
                    target.createNewFile();
                    fis = new FileInputStream(source);
                    fos = new FileOutputStream(target);
                    FileChannel fisChannel = fis.getChannel();
                    WritableByteChannel fosChannel = fos.getChannel();
                    fisChannel.transferTo(0, fisChannel.size(), fosChannel);
                    fisChannel.close();
                    fosChannel.close();
                    fis.close();
                    fos.close();

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 读取Excel的内容，第一维数组存储的是一行中格列的值，二维数组存储的是多少个行
     *
     * @param file       读取数据的源Excel
     * @param ignoreRows 读取数据忽略的行数，比喻行头不需要读入 忽略的行数为1
     * @return 读出的Excel中数据的内容
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static String[][] getData(File file, int ignoreRows) throws FileNotFoundException, IOException {
        List<String[]> result = new ArrayList<String[]>();
        int rowSize = 0;
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
        // 打开HSSFWorkbook
        POIFSFileSystem fs = new POIFSFileSystem(in);
        HSSFWorkbook wb = new HSSFWorkbook(fs);
        HSSFCell cell = null;
        for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) {
            HSSFSheet st = wb.getSheetAt(sheetIndex);
            // 第一行为标题，不取
            for (int rowIndex = ignoreRows; rowIndex <= st.getLastRowNum(); rowIndex++) {
                HSSFRow row = st.getRow(rowIndex);
                if (row == null) {
                    continue;
                }
                int tempRowSize = row.getLastCellNum() + 1;
                if (tempRowSize > rowSize) {
                    rowSize = tempRowSize;
                }
                String[] values = new String[rowSize];
                Arrays.fill(values, "");
                boolean hasValue = false;
                for (short columnIndex = 0; columnIndex <= row.getLastCellNum(); columnIndex++) {
                    String value = "";
                    cell = row.getCell(columnIndex);
                    if (cell != null) {
                        // 注意：一定要设成这个，否则可能会出现乱码,后面版本默认设置
                        // cell.setEncoding(HSSFCell.ENCODING_UTF_16);
                        switch (cell.getCellType()) {
                            case HSSFCell.CELL_TYPE_STRING:
                                value = cell.getStringCellValue();
                                break;
                            case HSSFCell.CELL_TYPE_NUMERIC:
                                if (HSSFDateUtil.isCellDateFormatted(cell)) {
                                    Date date = cell.getDateCellValue();
                                    if (date != null) {
                                        value = new SimpleDateFormat("yyyy-MM-dd").format(date);
                                    } else {
                                        value = "";
                                    }
                                } else {
                                    value = new DecimalFormat("0").format(cell

                                            .getNumericCellValue());
                                }
                                break;
                            case HSSFCell.CELL_TYPE_FORMULA:
                                // 导入时如果为公式生成的数据则无值
                                if (!cell.getStringCellValue().equals("")) {
                                    value = cell.getStringCellValue();
                                } else {
                                    value = cell.getNumericCellValue() + "";
                                }
                                break;
                            case HSSFCell.CELL_TYPE_BLANK:
                                break;
                            case HSSFCell.CELL_TYPE_ERROR:
                                value = "";
                                break;
                            case HSSFCell.CELL_TYPE_BOOLEAN:
                                value = (cell.getBooleanCellValue() == true ? "Y"

                                        : "N");
                                break;
                            default:
                                value = "";
                        }
                    }
                    if (columnIndex == 0 && value.trim().equals("")) {
                        break;
                    }
                    values[columnIndex] = rightTrim(value);
                    hasValue = true;
                }
                if (hasValue) {
                    result.add(values);
                }
            }
        }
        in.close();
        String[][] returnArray = new String[result.size()][rowSize];
        for (int i = 0; i < returnArray.length; i++) {
            returnArray[i] = (String[]) result.get(i);
        }
        return returnArray;
    }

    public static String rightTrim(String str) {
        if (str == null) {
            return "";
        }
        int length = str.length();
        for (int i = length - 1; i >= 0; i--) {
            if (str.charAt(i) != 0x20) {
                break;
            }
            length--;
        }
        return str.substring(0, length);
    }
}
